package by.dezhits.liltweets.adapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.widget.CursorAdapter;
import android.text.Html;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import by.dezhits.liltweets.ImageActivity;
import by.dezhits.liltweets.R;
import by.dezhits.liltweets.api.TwitterAPI;
import by.dezhits.liltweets.content.contract.TweetContract;
import by.dezhits.liltweets.content.contract.UsersContract;
import by.dezhits.liltweets.http.HttpRequestBuilder;
import by.dezhits.liltweets.images.ImageLoader;
import by.dezhits.liltweets.images.ImageLoader.ConvertOnLoadMode;
import by.dezhits.liltweets.service.HttpService;

public class TweetCursorAdapter extends CursorAdapter {

	ImageLoader loader;
	SimpleDateFormat simpleDateFormat;
	Context context;
	private static final  String TWITTER_DATE_FORMAT = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
	private static final String A_TAG_PREFIX = "<a href=\"\">";
	private static final String A_TAG_POSTFIX = "</a>";
	private static final String DOG = "@";
	private static final String RETWEETED_BY = "Retweeted by ";
	private static final String SECOND = "sec";
	private static final String MINUTE = "m";
	private static final String HOUR = "h";
	public TweetCursorAdapter(Context context, Cursor c) {
		super(context, c, true);
		loader = ImageLoader.getInstance();
		this.context = context;
		simpleDateFormat = new SimpleDateFormat(TWITTER_DATE_FORMAT,
				Locale.ENGLISH);
		simpleDateFormat.setLenient(true);
	}

	@Override
	public void bindView(View view, Context context, Cursor cursor) {

		TextView tvText = (TextView) view.findViewById(R.id.tv_tweet_text);
		TextView tvuserName = (TextView) view
				.findViewById(R.id.tv_tweet_user_name);
		TextView tvScreenName = (TextView) view
				.findViewById(R.id.tv_tweet_user_screen_name);
		TextView tvDate = (TextView) view.findViewById(R.id.tv_tweet_date);
		TextView retweet = (TextView) view.findViewById(R.id.tv_retweet);
		ImageView imageView = (ImageView) view.findViewById(R.id.iv_avatar);
		ImageView media = (ImageView) view.findViewById(R.id.iv_media);

		imageView.setTag(cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.USER_ID)));
		imageView.setImageBitmap(null);

		media.setImageBitmap(null);
		media.setVisibility(View.GONE);
		retweet.setVisibility(View.GONE);

		String text = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.TEXT));
		String link = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.LINK));
		String hashtags = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.HASHTAGS));
		if (link == null && hashtags == null) {
			tvText.setText(text);
		} else {
			StringBuilder sb = new StringBuilder(text);
			if (link != null) {
				int l = text.indexOf(link);
				if (l != -1) {
					sb.replace(l, l + link.length(), A_TAG_PREFIX + link
							+ A_TAG_POSTFIX);
				}
			}
			if (hashtags != null) {
				String[] tags = hashtags.split("#");
				String tag;
				for (int i = 0; i < tags.length; i++) {
					tag = "#" + tags[i];
					int start = sb.indexOf(tag);
					sb.replace(start, start + tag.length(), A_TAG_PREFIX
							+ tag + A_TAG_POSTFIX);
				}
			}
			text = sb.toString();
			tvText.setText(Html.fromHtml(text));
		}
		tvuserName.setText(cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.USER_NAME)));
		tvScreenName
				.setText(DOG
						+ cursor.getString(cursor
								.getColumnIndex(TweetContract.TweetsColumns.SCREEN_NAME)));

		String stringDate = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.CREATED_AT));
		Date date = getTwitterDate(stringDate);
		Date currentDate = new Date();
		tvDate.setText(getDateDifference(currentDate, date));
		String url = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.PROFILE_IMAGE_URL));
		loader.bind(imageView, url, ConvertOnLoadMode.ROUND, true);
		// loader.bind(this,imageView, url, ConvertOnLoadMode.ROUND);
		String media_url = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.IMAGE_URL));
		if (media_url != null) {
			media.setVisibility(View.VISIBLE);
			media.setTag(media_url);
			loader.bind(media, media_url, ConvertOnLoadMode.NORMAL, true);
			// loader.bind(this, media, media_url, ConvertOnLoadMode.NORMAL);

		}

		String retweeter = cursor.getString(cursor
				.getColumnIndex(TweetContract.TweetsColumns.RETWEETER));
		if (retweeter != null) {
			retweet.setVisibility(View.VISIBLE);
			retweet.setText(RETWEETED_BY + retweeter);
		}
	}

	@Override
	public View newView(final Context context, Cursor cursor,
			ViewGroup viewGroup) {
		View view = View.inflate(context, R.layout.adapter_tweet, null);
		final ImageView iv = (ImageView) view.findViewById(R.id.iv_media);
		iv.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String url = (String) iv.getTag();
				Intent intent = new Intent(context, ImageActivity.class);
				intent.putExtra(context.getString(R.string.image_url), url);
				context.startActivity(intent);
			}
		});

		final ImageView av = (ImageView) view.findViewById(R.id.iv_avatar);
		av.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				String id = (String) av.getTag();
				Uri uri = UsersContract.UsersColumns.CONTENT_URI;
				Cursor cursor = context.getContentResolver().query(uri, null,
						UsersContract.UsersColumns.ID + "='" + id + "'", null,
						null);
				if (cursor.getCount() > 0) {
					Intent intent = new Intent(
							HttpService.ACTION_ON_SUCCESS_USERPAGE);
					intent.putExtra("id", id);
					context.sendBroadcast(intent);
				} else {
					Intent intent = new Intent(context, HttpService.class);
					HttpRequestBuilder httpRequestBuilder = new HttpRequestBuilder();
					httpRequestBuilder.setType(HttpRequestBuilder.Type.GET);
					httpRequestBuilder
							.setTwitterRequest(HttpRequestBuilder.TwitterRequest.USERS_SHOW);
					httpRequestBuilder
							.setUrl(TwitterAPI.URL.TWITTER_USERS_SHOW_URL);
					httpRequestBuilder.appendQueryParameter(
							TwitterAPI.QueryParametr.USER_ID, id);
					intent.putExtra(HttpService.HTTP_REQUEST_BUILDER,
							httpRequestBuilder);
					context.startService(intent);
				}
			}

		});
		return view;
	}

	public Date getTwitterDate(String dateString) {
		try {
			Date date = simpleDateFormat.parse(dateString);
			return date;
		} catch (Exception e) {
			return null;
		}

	}

	public String getDateDifference(Date currentDate, Date date) {
		long dif = currentDate.getTime() - date.getTime();
		String s;
		if (dif < 60 * 1000)
			s = String.valueOf(dif / 1000) + SECOND;
		else if (dif < 60 * 60 * 1000)
			s = String.valueOf(dif / (60 * 1000)) + MINUTE;
		else if (dif < 24 * 60 * 60 * 1000)
			s = String.valueOf(dif / (60 * 60 * 1000)) + HOUR;
		else
			s = date.toString().substring(4, 10);
		return s;
	}

}
